<template>
	<div>
		<slot>
			<p class="text-sm">{{ showTime }}</p>
		</slot>
	</div>
</template>

<script setup>
import { ref } from 'vue'
import { onUnmounted, watch, computed } from 'vue'
import dayjs from './utils.js'

const props = defineProps({
	time: Number,
	format: {
		type: String,
		default: 'HH:mm:ss',
	},
})

const emits = defineEmits(['finish', 'change'])
const duration = ref(0)

// 倒计时结束
const close = () => {
	if (interval) {
		clearInterval(interval)
	}
}

// 开始倒计时
let interval
const start = () => {
	close()
	interval = setInterval(() => {
		durationFn()
	}, 1000)
}

watch(
	() => props.time,
	(val) => {
		duration.value = val
		start()
	},
	{
		immediate: true,
	}
)

// 倒计时的执行行为
const durationFn = () => {
	if (duration.value <= 0) {
		duration.value = 0
		emits('finish')
		close()
	} else {
		duration.value -= 1000
		emits('change')
	}
}

onUnmounted(() => {
	close()
})

// 显示时间格式
const showTime = computed(() => {
	return dayjs.duration(duration.value).format(props.format)
})
</script>

<style scoped lang="scss"></style>
